<script setup lang="ts">
import CategoryTreeView from '@/views/commodity/CategoryTreeView.vue'
import { ref, reactive, onMounted, nextTick } from 'vue'
import type { AttrVo, PageNationParams } from '@/api/attr/type'
import type { CategoryVo } from '@/api/category/type'
import { CascaderInstance, ElCascader, TableInstance } from 'element-plus'
import {
  addAttrRequest,
  attrDeleteRequest,
  attrUpdateRequest,
  getAttrVoGroupByCatalogID,
  queryAttrRequest,
} from '@/api/attr'
import { AttrGroupVo } from '@/api/attr-group/type'
import type { FormInstance, FormRules } from 'element-plus'

let attr = ref<AttrVo>({
  attrID: 0,
  attrName: '',
  searchType: false,
  icon: '',
  attrValue: [],
  attrType: undefined,
  enable: false,
  catalogID: 0,
  showDescription: false,
  attrGroupID: undefined,
  categoryName: '',
  attrGroupName: '',
})

// 分类信息集合
const categoryVos = ref<CategoryVo[]>([])
// 点击分类树的叶子节点时触发，查询对应分类的属性
const queryAttr = async (data) => {
  pageNationParams.value.catalogID = data
  await queryAttrRequest(pageNationParams.value).then((res) => {
    attrVos.value = res.items
    count.value = res.count
  })
}
// 从子组件（分类树）中获取分类集合
const getCategoryVos = async (data) => {
  categoryVos.value = data
}
// 控制新增属性对话框显示，true-弹出，false=隐藏
const attrDialogVisible = ref<boolean>(false)
// 属性类型
const attrType = [
  { value: 0, label: '销售属性' },
  { value: 1, label: '规格参数' },
]
// 是否可检索
const searchType = ref<boolean>(false)
// 级联选择器实例对象
const cascaderRef = ref<CascaderInstance>()
// 属性分组集合
const attrGroups = ref<AttrGroupVo[]>([])
// 属性总条数
const count = ref<number>(0)
// 级联选择器的值发生变化时触发，根据分类id查询属性值
const searchAttrGroup = async () => {
  attr.value.catalogID = attr.value.catalogID[2]
  await getAttrVoGroupByCatalogID(attr.value.catalogID).then((res) => {
    attrGroups.value = res
  })
}

const attrProp = { value: 'categoryID', label: 'name', children: 'children' }
// 新增规格参数按钮回调事件
const addAttr = () => {
  attrDialogVisible.value = true
  attr = ref<AttrVo>({
    attrID: 0,
    attrName: '',
    searchType: false,
    icon: '',
    attrValue: [],
    attrType: undefined,
    enable: false,
    catalogID: 0,
    showDescription: false,
    attrGroupID: undefined,
    categoryName: '',
    attrGroupName: '',
  })
  nextTick(() => {
    attrFormRef.value.clearValidate('attrName')
    attrFormRef.value.clearValidate('attrType')
    attrFormRef.value.clearValidate('attrValue')
    attrFormRef.value.clearValidate('icon')
    attrFormRef.value.clearValidate('catalogID')
    attrFormRef.value.clearValidate('attrGroupID')
    attrFormRef.value.clearValidate('searchType')
    attrFormRef.value.clearValidate('showDescription')
    attrFormRef.value.clearValidate('enable')
  })
}
// 属性表单实例
const attrFormRef = ref<FormInstance>()
// 可靠值校验规则
const validateattrValue = (rule: any, value: any, callback: any) => {
  if (value == '') {
    return new Error('请输入可选值')
  } else {
    new callback()
  }
}
// 属性表单校验规则
const rules = reactive<FormRules<AttrVo>>({
  attrName: [
    { required: true, message: '请输入属性名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30之间', trigger: 'blur' },
  ],
  attrType: [{ required: true, message: '请选择属性类型', trigger: 'blur' }],
  attrValue: [{ validator: validateattrValue, trigger: 'blur' }],
  icon: [
    { required: true, message: '请输入图标', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30之间', trigger: 'blur' },
  ],
  catalogID: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  attrGroupID: [{ required: true, message: '请选择分组', trigger: 'blur' }],
  searchType: [{ required: true, message: '请选择是否可检索', trigger: 'blur' }],
  showDescription: [{ required: true, message: '请选择是否展示在介绍上', trigger: 'blur' }],
  enable: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
})
// 页码
const currentPage = ref<number>(1)
const pageSize = ref<number>(5)
const catalogID = ref<number>(0)
const condition = ref<string>('')
const pageNationParams = ref<PageNationParams>({
  pageIndex: currentPage.value,
  pageSize: pageSize.value,
  catalogID: catalogID.value,
  condition: condition.value,
})
// 属性集合
const attrVos = ref<AttrVo[]>([])
// 属性表单确定按钮单击事件
const attrConfirm = () => {
  attrFormRef.value.validate(async (valid) => {
    if (valid) {
      // 若attrID==0，则发送新增请求
      if (attr.value.att === 0) {
        await addAttrRequest(attr.value)
          .then((res) => {
            attrDialogVisible.value = false
            return queryAttrRequest(pageNationParams.value)
          })
          .then((res) => {
            attrVos.value = res.items
            count.value = res.count
          })
      } else {
        await attrUpdateRequest(attr.value)
          .then((res) => {
            attrDialogVisible.value = false
            return queryAttrRequest(pageNationParams.value)
          })
          .then((res) => {
            attrVos.value = res.items
            count.value = res.count
          })
      }
    }
  })
}
// 改变页码长度后重新查询
const handleSizeChange = async () => {
  pageNationParams.value.pageSize = pageSize.value
  await queryAttrRequest(pageNationParams.value).then((res) => {
    attrVos.value = res.items
    count.value = res.count
  })
}
// 改变页码后重新查询
const handleCurrentChange = async () => {
  pageNationParams.value.pageIndex = currentPage.value
  await queryAttrRequest(pageNationParams.value).then((res) => {
    attrVos.value = res.items
    count.value = res.count
  })
}
// 搜索框输入值
const attrName = ref<string>('')
// 查询按钮单击事件
const searchAttr = async () => {
  pageNationParams.value.pageIndex = 1
  pageNationParams.value.catalogID = 0
  pageNationParams.value.condition = attrName.value
  await queryAttrRequest(pageNationParams.value).then((res) => {
    attrVos.value = res.items
    count.value = res.count
  })
}
// 修改皇家岛单击事件
const editAttr = async (row) => {
  attrDialogVisible.value = true
  Object.assign(attr.value, row)
  // 查询属性分组
  await getAttrVoGroupByCatalogID(attr.value.catalogID as number).then((res) => {
    attrGroups.value = res
  })
}
// 删除属性按钮确定按钮单击事件
const deleteAttr = async (row) => {
  attrIDs.value.push(row.attrID)
  await attrDeleteRequest(attrIDs.value).then((res) => {
    queryAttrRequest(pageNationParams.value).then((res) => {
      attrVos.value = res.items
      count.value = res.count
    })
  })
}
// 属性id集合
const attrIDs = ref<number[]>([])
// 属性表格实例
const attrTableRef = ref<TableInstance>()
// 批量删除按钮单击事件
const batchDelete = async () => {
  attrTableRef.value.getSelectionRows().forEach((item) => {
    attrIDs.value.push(item.attrID)
  })
  await queryAttrRequest(pageNationParams.value).then((res) => {
    attrVos.value = res.items
    count.value = res.count
  })
}
</script>

<template>
  <div class="container">
    <el-row>
      <!--      分类树-->
      <el-col :span="6">
        <CategoryTreeView @sendCategoryID="queryAttr" @sendCategoryVos="getCategoryVos" />
      </el-col>
      <!--      属性列表-->
      <el-col :span="18">
        <!--        搜索按钮-->
        <div>
          <el-form inline>
            <el-form-item>
              <el-input placeholder="组名" v-model="attrName"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="searchAttr">查询</el-button>
              <el-button type="primary" @click="addAttr">新增</el-button>
              <el-popconfirm title="确定要删除吗?" @confirm="batchDelete">
                <template #reference>
                  <el-button type="danger">批量删除</el-button>
                </template>
              </el-popconfirm>
            </el-form-item>
          </el-form>
        </div>
        <!--        显示属性表格-->
        <el-table
          style="width: 100%"
          border
          :data="attrVos"
          show-overflow-tooltip
          ref="attrTableRef"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column type="index" label="序号" align="center" width="60" />
          <el-table-column prop="attrName" label="属性名" align="center" width="120" />
          <el-table-column prop="searchType" label="可检索" align="center" width="70">
            <template #default="scope">{{ scope.row.searchType == false ? '否' : '是' }}</template>
          </el-table-column>
          <el-table-column prop="attrType" label="值类型" align="center" width="90">
            <template #default="scope">
              {{ scope.row.attrType == 0 ? '销售属性' : '规格参数' }}
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="图标" align="center" width="80" />
          <el-table-column prop="attrValue" label="可选值" align="center" width="120" />
          <el-table-column prop="enable" label="启用" align="center" width="60">
            <template #default="scope">{{ scope.row.enabled ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column
            prop="attrGroupName"
            label="所属分组"
            align="center"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="categoryName"
            label="所属分类"
            align="center"
            width="120"
          ></el-table-column>
          <el-table-column prop="showDescription" label="快速展示" align="center" width="100">
            <template #default="scope">{{ scope.row.showDescription ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button type="success" @click="editAttr(scope.row)">修改</el-button>
              <el-popconfirm title="确定要删除吗?" @confirm="deleteAttr(scope.row)">
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="margin: 1rem 0"
          :total="count"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
    <!--    添加和修改规格参数对话框-->
    <el-dialog
      :title="attr.attrID === 0 ? '新增规格参数' : '修改规格参数'"
      width="600"
      v-model="attrDialogVisible"
    >
      <el-form
        label-width="auto"
        :model="attr"
        style="padding: 1rem"
        ref="attrFormRef"
        :rules="rules"
      >
        <el-form-item label="属性名称" prop="attrName" style="width: 20rem">
          <el-input v-model="attr.attrName"></el-input>
        </el-form-item>
        <el-form-item label="属性类型" prop="attrType" style="width: 15rem">
          <el-select v-model="attr.attrType">
            <el-option
              v-for="item in attrType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可选值" prop="attrValue">
          <el-input-tag v-model="attr.attrValue" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" style="width: 10rem">
          <el-input v-model="attr.icon"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" style="width: 15rem" prop="catalogID">
          <el-cascader
            v-model="attr.catalogID"
            :options="categoryVos"
            :props="attrProp"
            filterable
            ref="cascaderRef"
            @change="searchAttrGroup"
          />
        </el-form-item>
        <el-form-item label="所属分组" prop="attrGroupID">
          <el-select style="width: 15rem" v-model="attr.attrGroupID">
            <el-option
              v-for="attrGroup in attrGroups"
              :key="attrGroup.attrGroupID"
              :label="attrGroup.attrGroupName"
              :value="attrGroup.attrGroupID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可检索" prop="searchType">
          <el-switch v-model="searchType"></el-switch>
        </el-form-item>
        <el-form-item label="快速展示" prop="showDescription">
          <el-switch v-model="attr.showDescription"></el-switch>
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <el-switch v-model="attr.enable"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="margin-top: 1rem">
          <el-button @click="attrDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="attrConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped></style>
